package com.xcc.observerpattern.demo1;

import lombok.Data;

import java.util.ArrayList;
import java.util.List;

/**
 * @Description: WeatherData
 * @Author: xiechuang
 * @Date: 2022/6/28
 */
@Data
public class WeatherData implements Subject {

    // 观察者列表
    private List<Observer> observers;
    // 温度值
    private float temperature;
    // 湿度值
    private float humidity;
    // 气压值
    private float pressure;

    public WeatherData() {
        observers = new ArrayList();
    }

    @Override
    public void registerObserver(Observer observer) {
        observers.add(observer);
    }

    @Override
    public void removeObserver(Observer observer) {
        int i = observers.indexOf(observer);
        if (i >= 0) {
            observers.remove(i);
        }
    }

    @Override
    public void notifyObservers() {
        for (int i = 0; i < observers.size(); i++) {
            Observer observer = observers.get(i);
            observer.update(temperature, humidity, pressure);
        }
    }

    /**
     * 值发生改变，调用通知观察者方法
     */
    public void measurementsChanged() {
        notifyObservers();
    }

    /**
     * 设置值
     *
     * @param temperature
     * @param humidity
     * @param pressure
     */
    public void setMeasurements(float temperature, float humidity, float pressure) {
        this.temperature = temperature;
        this.humidity = humidity;
        this.pressure = pressure;
        measurementsChanged();
    }

}
